package com.company.test29;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.util.Scanner;

/**
 * Created by v on 16-11-29.
 */
public class Test29_14 extends JApplet{
    private JProgressBar progressBar=new JProgressBar();
    private Path path=new Path();
    private JButton copy=new JButton("copy");

    public Test29_14(){
        progressBar.setStringPainted(true);
        add(progressBar,BorderLayout.NORTH);
        add(path,BorderLayout.CENTER);
        JPanel panel=new JPanel();
        panel.add(copy);
        add(panel,BorderLayout.SOUTH);

        copy.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Copy copy=new Copy(path.field1.getText(),
                        path.field2.getText());

                copy.addPropertyChangeListener(new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                        if ("progress".equals(evt.getPropertyName())){
                            progressBar.setValue((Integer) evt.getNewValue());
                        }
                    }
                });

                copy.execute();
            }
        });
    }

    private class Copy extends SwingWorker<Integer,Integer>{
        String path1;
        String path2;

        public Copy(String path1,String path2){
            this.path1=path1;
            this.path2=path2;
        }

        @Override
        protected Integer doInBackground() throws Exception {
            File file1=new File(path1);
            File file2=new File(path2);

            if(!file2.exists()){
                file2.createNewFile();
            }

            DataInputStream input=new DataInputStream(new BufferedInputStream(new FileInputStream(file1)));
            DataOutputStream output=new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file2)));

            long number=0;

            while (number<file1.length()){
                output.write(input.readByte());
                number++;

                setProgress((int) (100*number/file1.length()));
            }

            input.close();
            output.close();

            return null;
        }
    }

    private class Path extends JPanel{
        private JLabel from=new JLabel("From");
        private JLabel to=new JLabel("To");
        private JTextField field1=new JTextField();
        private JTextField field2=new JTextField();

        public Path(){
            setLayout(new GridLayout(4,1));
            add(from);
            add(field1);
            add(to);
            add(field2);
        }
    }
}
